package com.zzedu.framework.config;

import com.zzedu.system.domain.ConfigI18n;
import com.zzedu.system.service.ISysConfigI18nService;
import com.google.common.collect.Maps;
import jakarta.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.AbstractMessageSource;
import org.springframework.stereotype.Component;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.Map;

@Component("messageSource")
public class MessageResourceDataBaseExtension extends AbstractMessageSource {
    private final static Logger logger = LoggerFactory.getLogger(MessageResourceDataBaseExtension.class);
    private final Map<String, MessageFormat> cachedMessageFormats = Maps.newConcurrentMap();

    @Autowired
    ISysConfigI18nService configI18nService;


    @Override
    @Nullable
    protected MessageFormat resolveCode(String code, Locale locale) {
        ConfigI18n configI18n = this.configI18nService.getCodeAndLanguage(code, locale.getLanguage()+"_"+locale.getCountry());
        if (null != configI18n) {
            String lange[] = configI18n.getLanguage().split("_");
            Locale local = new Locale(lange[0], lange[1]);
            return createMessageFormat(configI18n.getLanguageValue(), local);
        }else{
            logger.error("未找到【"+code+"】对应说明,"+locale.getLanguage()+"_"+locale.getCountry());
            return createMessageFormat("未找到【"+code+"】对应说明,"+locale.getLanguage()+"_"+locale.getCountry(), locale);
        }


    }
}